--Lua bit32 Library
local bit32 = {}
function bit32.bxorRemake(a, b)
    local r = 0
    for i = 0, 31 do
        local x = a // 2^i % 2
        local y = b // 2^i % 2
        if x ~= y then
            r = r + 2^i
        end
    end
    return r % 256
end
function bit32.band(a, b)
    return a & b
end
function bit32.bor(a, b)
    return a | b
end
function bit32.bxor(a, b)
    return a ~ b
end
function bit32.bnot(a)
    return ~a
end
function bit32.lshift(a, n)
    return a << n
end
function bit32.rshift(a, n)
    return a >> n
end
function bit32.arshift(a, n)
    if a >= 0 then
        return a >> n
    else
        local mask = 0xFFFFFFFF
        a = a & mask
        return (a >> n) & mask
    end
end
function bit32.lrotate(a, n)
    n = n % 32
    return (a << n) | (a >> (32 - n))
end
function bit32.rrotate(a, n)
    n = n % 32
    return (a >> n) | (a << (32 - n))
end
function bit32.tobits(a)
    local t = {}
    for i = 31, 0, -1 do
        if a & (1 << i) ~= 0 then
            t[#t + 1] = '1'
        else
            t[#t + 1] = '0'
        end
    end
    return table.concat(t)
end
function bit32.frombits(s)
    local n = 0
    for i = 1, #s do
        n = n * 2 + (s:sub(i, i) == '1' and 1 or 0)
    end
    return n
end
local function is_integer(n)
    return math.type(n) == "integer"
end
local function check_integer(a, b)
    if not is_integer(a) or not is_integer(b) then
        error("Both arguments must be integers", 2)
    end
end
local original_band = bit32.band
bit32.band = function(a, b)
    check_integer(a, b)
    return original_band(a, b)
end
local original_bor = bit32.bor
bit32.bor = function(a, b)
    check_integer(a, b)
    return original_bor(a, b)
end
local original_bxor = bit32.bxor
bit32.bxor = function(a, b)
    check_integer(a, b)
    return original_bxor(a, b)
end
local original_bnot = bit32.bnot
bit32.bnot = function(a)
    if not is_integer(a) then
        error("Argument must be an integer", 2)
    end
    return original_bnot(a)
end
local original_lshift = bit32.lshift
bit32.lshift = function(a, n)
    check_integer(a, n)
    return original_lshift(a, n)
end
local original_rshift = bit32.rshift
bit32.rshift = function(a, n)
    check_integer(a, n)
    return original_rshift(a, n)
end
local original_arshift = bit32.arshift
bit32.arshift = function(a, n)
    check_integer(a, n)
    return original_arshift(a, n)
end
local original_lrotate = bit32.lrotate
bit32.lrotate = function(a, n)
    check_integer(a, n)
    return original_lrotate(a, n)
end
local original_rrotate = bit32.rrotate
bit32.rrotate = function(a, n)
    check_integer(a, n)
    return original_rrotate(a, n)
end
return bit32